<?php
/**
*
* @package phpBB3
* @version $Id$
* @copyright (c) 2005 phpBB Group
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/**
*/

/**
* @ignore
*/
 
define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
require_once($phpbb_root_path . 'common.' . $phpEx);
require_once($phpbb_root_path . 'includes/functions_display.' . $phpEx);
require_once($phpbb_root_path . 'sv_common.' . $phpEx);
require_once($phpbb_root_path . 'includes/functions_user.' . $phpEx);

require_once( 'Facebook/FacebookSession.' . $phpEx);
require_once( 'Facebook/FacebookRedirectLoginHelper.' . $phpEx );
require_once( 'Facebook/FacebookRequest.' . $phpEx );
require_once( 'Facebook/FacebookResponse.' . $phpEx );
require_once( 'Facebook/FacebookSDKException.' . $phpEx );
require_once( 'Facebook/FacebookRequestException.' . $phpEx );
require_once( 'Facebook/FacebookAuthorizationException.' . $phpEx );
require_once( 'Facebook/GraphObject.' . $phpEx );
require_once( 'Facebook/Entities/AccessToken.' . $phpEx );
require_once( 'Facebook/HttpClients/FacebookHttpable.' . $phpEx );
require_once( 'Facebook/HttpClients/FacebookCurlHttpClient.' . $phpEx );
require_once( 'Facebook/HttpClients/FacebookCurl.' . $phpEx );
require_once( 'Facebook/GraphUser.' . $phpEx );

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\Entities\AccessToken;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\GraphUser;

FacebookSession::setDefaultApplication(get_fb_app_id(), get_fb_app_secret());

// Start session management
$user->session_begin();
$auth->acl($user->data);
$user->setup('stockvirtual');

$money = $user->data['user_money'];
$user_id 	= $user->data['user_id'];

$is_iOS = is_iOS($_SERVER['HTTP_USER_AGENT']);

// Check if the user is logged on
if ($user_id != ANONYMOUS)
{
	// list all holding stock.
	//$r = list_holding_stock('', 0, '', true, true);
	
	if ($is_iOS)
		$r = list_holding_stock('', 0, '', true, true, false);
	else
		$r = list_holding_stock('', 0, '', true, true);
		
	$holding_any_stock	= $r['holding_any_stock'];
	$shorting_any_stock = $r['shorting_any_stock'];
}
// if not logged on, check if there is a FB session to use
else
{
	session_start();
	
	$helper = new FacebookRedirectLoginHelper('http://stockvirtual.info/index.php');	
	
	if (!isset($_GET['state']))
	{
		// no state, so this is a fresh start. Let's get a login URL for potential logins
		try {
			//echo "get url... <BR>";
			$loginUrl = $helper->getLoginUrl();
			//echo "url:$loginUrl <BR>";
		} catch(FacebookRequestException $ex) {
			//echo "FB returns error<BR>";
		} catch(\Exception $ex) {
	  		// When validation fails or other local issues
	  		//echo "other errors<BR>";	
	  		//echo $ex;
		}	
	}
	else
	{
		// got state, so we are in the second step: the user is redirected back here. Try to log on. 	
		try {
			//echo "getSessionFromRedirect... <BR>";
	  		$session = $helper->getSessionFromRedirect();
	  		
		} catch(FacebookRequestException $ex) {
	  		// When Facebook returns an error
	  		//echo "FB returns error<BR>";
	  		//echo $ex;
	  		//echo "<BR>";
		} catch(\Exception $ex) {
	  		// When validation fails or other local issues
	  		//echo "other errors<BR>";
	  		//echo $ex;
	  		//echo "<BR>";
		}
		
		if ($session) {
	  		// Logged in
	  		//echo "got session  <BR>";
	  		$request = new FacebookRequest($session, 'GET', '/me');
			$response = $request->execute();
			$obj = $response->getGraphObject(GraphUser::className());	
						
			if ($obj) 
			{
				$me	= $obj->asArray();
				//print_r($me);
				
				// try to login the user
				if (login_fb_user($me['id']) == false)
				{							
					// check if the user name already exist
					if (username_exist($me['name']))
					{				
						$fb_user_info = json_encode ($me);
								
						// redirect to the select name page
						$url = "{$phpbb_root_path}name_conflict.$phpEx?fb_user_info=$fb_user_info";	
						sv_redirect($url);		
						//echo "$fb_user_info <BR>";
					}
						
			  		if (register_fb_user($me['id'], $me['name'], $me['first_name'], $me['last_name'], '', $me['link'], $me['gender'], $me['timezone'], $me['locale'], $me['verified']))
					{
						// refresh
						$url = append_sid("{$phpbb_root_path}/index.$phpEx", '');	
						redirect($url, false, true);
						//echo "<a href='" . $url . "'>Redirecting...</a><br /><br />" . $url;
					}
				}
				else
				{
					//echo "logged on  <BR>";
				}
			} 			
  		}	  		
  		
  		{
	  		// we fail to log the user in, so we still need a url for future login
	  		try {
				//echo "get url... <BR>";
				$loginUrl = $helper->getLoginUrl();
				//echo "url:$loginUrl <BR>";
			} catch(FacebookRequestException $ex) {
				//echo "FB returns error<BR>";
			} catch(\Exception $ex) {
	  			// When validation fails or other local issues
	  			//echo "other errors<BR>";	
	  			//echo $ex;
			}	
  		}
	}
	
/*
	// Create our Application instance (replace this with your appId and secret).
	$facebook = new Facebook(array(
		'appId'  => get_fb_app_id(),
  		'secret' => get_fb_app_secret(),
  		'cookie' => true,
	));

	$loginUrl = $facebook->getLoginUrl();  			 
	$uid = $facebook->getUser();
	
	echo "loginUrl:$loginUrl <BR>";
	echo "uid:$uid <BR>";
	
	if ($uid)
	{
		try 
	  	{    	
		  	
	    	$me = $facebook->api('/me');
	  	} 
	  	catch (FacebookApiException $e) 
	  	{
		  	echo "<!-- fail to call FB api ";
		  	$r = $e->getResult();
		  	echo htmlspecialchars(print_r($r, true));	  	
		  	echo " -->";
			error_log($e);
			$me = null;
		}
	}

	if ($me) 
	{
		// try to login the user
		if (login_fb_user($me['id']) == false)
		{		
			// check if the user is requesting to register
			$state		= request_var('state', '');
			if ($state != '')
			{
				// check if the user name already exist
				if (username_exist($me['name']))
				{				
					$fb_user_info = json_encode ($me);
						
					// redirect to the select name page
					$url = "{$phpbb_root_path}name_conflict.$phpEx?fb_user_info=$fb_user_info";	
					sv_redirect($url);		
				}
				
	  			if (register_fb_user($me['id'], $me['name'], $me['first_name'], $me['last_name'], '', $me['link'], $me['gender'], $me['timezone'], $me['locale'], $me['verified']))
				{
					// refresh
					$url = append_sid("{$phpbb_root_path}/index.$phpEx", '');	
					redirect($url, false, true);
					echo "<a href='" . $url . "'>Redirecting...</a><br /><br />" . $url;
				}				
			}
		}
	} 
	*/
}

//echo "done<BR>";

// show ranking directly on index page if the user is not logged in.
if ($user_id == ANONYMOUS)
{	
	// list highest 20 user values in the latest date. 
	$show_user_value = list_user_value_ranking(20);
	
	// list highest 20 user ROI in 1 month period. 
	$show_1_month_roi = list_user_roi_ranking(30, 'roi_1_month_list', 20);
}

if (is_newbie($user_id))
{
	$show_welcome_newbie	= true;
	$show_rule 				= true;	
}

// get personal setting
$news_max_number = 10;
$market_info_option = 0;
$result = get_personal_setting($user_id);
if (isset($result))
{
	$news_max_number 	= $result['news_max_number'];
	$market_info_option	= $result['market_info'];
	$allow_ad			= $result['allow_ad'];
}

// show news
if ($news_max_number != 0)
{
	list_news($user_id, $news_max_number);
	$show_news = true;							// we always shows the news section since users can click to get more news. 
}

// list all related equity change events.
list_equity_change_event($user_id);

$show_statistics = false;
if ($auth->acl_getf_global('m_'))
{
	$show_statistics = true;	
}
$show_adm_query = false;
if ($auth->acl_getf_global('m_'))
{
	$show_adm_query = true;
}
$show_adm_equity_change = false;
if ($auth->acl_getf_global('m_'))
{
	$show_adm_equity_change = true;
}
$show_news_console = false;
if ($auth->acl_getf_global('m_'))
{
	$show_news_console = true;
}

$is_following_anyone = is_following_anyone($user_id);

// Don't show knowledge to save loading time
//$show_knowledge = list_knowledge_titles();
$show_knowledge = false;

// Take 33% chance to show a poll.
if (rand(1 , 3) == 1 && $user_id != ANONYMOUS)
{
	list_poll();
}

display_forums('', $config['load_moderators']);


// Assign index specific vars
$template->assign_vars(array(

	'FORUM_IMG'				=> $user->img('forum_read', 'NO_NEW_POSTS'),
	'FORUM_NEW_IMG'			=> $user->img('forum_unread', 'NEW_POSTS'),
	'FORUM_LOCKED_IMG'		=> $user->img('forum_read_locked', 'NO_NEW_POSTS_LOCKED'),
	'FORUM_NEW_LOCKED_IMG'	=> $user->img('forum_unread_locked', 'NO_NEW_POSTS_LOCKED'),

	'S_LOGIN_ACTION'			=> append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=login'),
	'S_BUY_ACTION'				=> append_sid("{$phpbb_root_path}buy.$phpEx", ''),
	'S_SELL_ACTION'				=> append_sid("{$phpbb_root_path}sell.$phpEx", ''),
	'S_SHORT_SELL_ACTION'		=> append_sid("{$phpbb_root_path}short_sell.$phpEx", ''),
	'S_SHORT_COVER_ACTION'		=> append_sid("{$phpbb_root_path}short_cover.$phpEx", ''),
	'S_PERFORMANCE_ACTION'		=> append_sid("{$phpbb_root_path}performance.$phpEx", ''),
	'S_HISTORY_ACTION'			=> append_sid("{$phpbb_root_path}history.$phpEx", ''),
	'S_RANKING_ACTION'			=> append_sid("{$phpbb_root_path}ranking.$phpEx", ''),
	'S_PERSONAL_SETTING_ACTION'	=> append_sid("{$phpbb_root_path}personal_setting.$phpEx", ''),
	'S_STOCK_SELECTION_ACTION'	=> append_sid("{$phpbb_root_path}stock_selection.$phpEx", ''),
	'S_STOCK_NEWS_ACTION'		=> append_sid("{$phpbb_root_path}stock_news.$phpEx", ''),
	'S_RULE'					=> append_sid("{$phpbb_root_path}rule.$phpEx", ''),
	'S_ABOUT'					=> append_sid("{$phpbb_root_path}sv_about.$phpEx", ''),
	'S_FAQ'						=> append_sid("{$phpbb_root_path}sv_faq.$phpEx", ''),
	'S_STATISTICS'				=> append_sid("{$phpbb_root_path}statistics.$phpEx", ''),
	'S_ADM_QUERY'				=> append_sid("{$phpbb_root_path}adm_query.$phpEx", ''),
	'S_ADM_EQUITY_CHANGE'		=> append_sid("{$phpbb_root_path}adm_equity_change.$phpEx", ''),
	'S_NEWS_CONSOLE'			=> append_sid("{$phpbb_root_path}news_console.$phpEx", ''),
	'S_QUERY_USER'				=> append_sid("{$phpbb_root_path}query_user.$phpEx", 'mode=query_user'),
	'S_FOLLOW_INFO'				=> append_sid("{$phpbb_root_path}follow_info.$phpEx", ''),
	'S_FB_FRIEND_INFO'			=> append_sid("{$phpbb_root_path}fb_friend_info.$phpEx", ''),
	'S_FOLLOW_STATISTICS'		=> append_sid("{$phpbb_root_path}follow_statistics.$phpEx", ''),
	'S_MANAGE_POLL'				=> append_sid("{$phpbb_root_path}manage_poll.$phpEx", ''),
	'S_DELEGATION_WHILE_SITE'	=> append_sid("{$phpbb_root_path}delegation_whole_site.$phpEx", ''),
	'S_FB_LOGIN_URL'			=> $loginUrl,
	'S_FULL_RANKING'				=> append_sid("{$phpbb_root_path}full_ranking.$phpEx", ''),
	'S_FULL_RANKING_1_MONTH_ROI'	=> append_sid("{$phpbb_root_path}full_ranking.$phpEx", 'mode=1_month_roi'),
	
	'S_DISPLAY_BIRTHDAY_LIST'	=> ($config['load_birthdays']) ? true : false,

	'S_TO_BUY_DELEGATION_LIST'	=> $to_buy_delegation_list,
	'S_TO_SELL_DELEGATION_LIST'	=> $to_sell_delegation_list,
	
	'S_EQUITY_CHANGE_EVENT_LIST'=> $equity_change_event_list,
	
	'U_MONEY'					=> number_format($money),
	'U_USERNAME'				=> $user->data['username'],
	'S_HIDE_NAV_LINK'			=> true,
	'S_SHOW_RULE'				=> $show_rule,
	'S_SHOW_WELCOME_NEWBIE'		=> $show_welcome_newbie,
	'S_SHOW_STATISTICS'			=> $show_statistics,
	'S_SHOW_ADM_QUERY'			=> $show_adm_query,
	'S_SHOW_ADM_EQUITY_CHANGE'	=> $show_adm_equity_change,
	'S_SHOW_NEWS_CONSOLE'		=> $show_news_console,	
	'S_SHOW_KNOWLEDGE'			=> $show_knowledge,
	'S_SHOW_NEWS'				=> $show_news,
	
	'MARKET_INFO_OPTION'		=> $market_info_option,
	
	'S_HOLDING_ANY_STOCK'		=> $holding_any_stock, 
	'S_SHORTING_ANY_STOCK'		=> $shorting_any_stock, 
	
	'U_MARK_FORUMS'		=> ($user->data['is_registered'] || $config['load_anon_lastread']) ? append_sid("{$phpbb_root_path}index.$phpEx", 'hash=' . generate_link_hash('global') . '&amp;mark=forums') : '',
	'U_MCP'				=> ($auth->acl_get('m_') || $auth->acl_getf_global('m_')) ? append_sid("{$phpbb_root_path}mcp.$phpEx", 'i=main&amp;mode=front', true, $user->session_id) : '',

	'SHOW_USER_VALUE'	=>	$show_user_value,
	'SHOW_1_MONTH_ROI'	=>	$show_1_month_roi,
	
	'IS_FOLLOWING_ANYONE'	=>	$is_following_anyone,
	'ALLOW_AD'				=> $allow_ad,
	
	'S_INCLUDE_JQUERY'				=> true,				// to instruct sv_overall_header.html to include jQuery. 
	'S_INCLUDE_JQUERY_UI'			=> true,				// to instruct sv_overall_header.html to include jQuery UI. 
		
	'S_USE_HTML5_CANVAS'			=> $is_iOS, 
));

// Output page
page_header($user->lang['INDEX']);

$template->set_filenames(array(
	'body' => 'index_body.html')
);

page_footer();

?>